<?php
$lockDir = dirname(__DIR__) . '/../install/';
$firstLockFile = $lockDir . 'first.lock';
$secondLockFile = $lockDir . 'second.lock';
$sqlFile = $lockDir . 'database.sql';
$configFile = dirname($lockDir) . '/database.php';

if (!file_exists($firstLockFile)) {
    header('Location: index.php');
    exit;
}

if (file_exists($secondLockFile)) {
    header('Location: third.php');
    exit;
}

$dbHost = $_POST['db_host'] ?? 'localhost';
$dbUser = $_POST['db_user'] ?? '';
$dbPass = $_POST['db_pass'] ?? '';
$dbName = $_POST['db_name'] ?? '';
$dbPort = $_POST['db_port'] ?? '3306';

$error = '';
$success = false;
$connection = null;

if ($_POST['submit'] ?? '') {
    try {
        if (!file_exists($sqlFile)) {
            throw new Exception('数据库文件不存在: ' . $sqlFile);
        }

        $connection = @new mysqli($dbHost, $dbUser, $dbPass, '', $dbPort);
        
        if ($connection->connect_error) {
            throw new Exception('数据库连接失败: ' . $connection->connect_error);
        }

        if (!$connection->select_db($dbName)) {
            $createDb = $connection->query("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            if (!$createDb) {
                throw new Exception('数据库创建失败: ' . $connection->error);
            }
            $connection->select_db($dbName);
        }

        $sqlContent = file_get_contents($sqlFile);
        if ($sqlContent === false) {
            throw new Exception('无法读取数据库文件');
        }

        $queries = array_filter(array_map('trim', explode(';', $sqlContent)));
        
        foreach ($queries as $query) {
            if (!empty($query) && substr($query, 0, 2) != '--') {
                $result = $connection->query($query);
                if (!$result && $connection->errno) {
                    throw new Exception('SQL执行错误: ' . $connection->error . ' - 在语句: ' . substr($query, 0, 100));
                }
            }
        }

        $checkTable = $connection->query("SELECT 1 FROM `config` LIMIT 1");
        if (!$checkTable) {
            throw new Exception('数据表导入验证失败');
        }

        $configContent = "<?php
function conn() {
    static \$connection = null;
    if (\$connection === null) {
        \$connection = new mysqli('{$dbHost}', '{$dbUser}', '{$dbPass}', '{$dbName}', {$dbPort});
        if (\$connection->connect_error) {
            throw new Exception('数据库连接失败: ' . \$connection->connect_error);
        }
        \$connection->set_charset('utf8mb4');
    }
    return \$connection;
}
?>";

        if (file_put_contents($configFile, $configContent) === false) {
            throw new Exception('数据库配置文件创建失败');
        }

        $success = true;
        file_put_contents($secondLockFile, date('Y-m-d H:i:s'));
        header('Location: third.php');
        exit;

    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库配置 - QQ速刷对接系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/bootstrap-icons.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title mb-0">数据库配置</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($error): ?>
                            <div class="alert alert-danger">
                                <i class="bi bi-x-circle"></i> <?= htmlspecialchars($error) ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <i class="bi bi-check-circle"></i> 数据库安装成功，正在跳转...
                            </div>
                        <?php else: ?>
                            <form method="post">
                                <div class="mb-3">
                                    <label class="form-label">数据库地址</label>
                                    <input type="text" name="db_host" class="form-control" value="<?= htmlspecialchars($dbHost) ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">数据库端口</label>
                                    <input type="text" name="db_port" class="form-control" value="<?= htmlspecialchars($dbPort) ?>" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">数据库用户名</label>
                                    <input type="text" name="db_user" class="form-control" value="<?= htmlspecialchars($dbUser) ?>" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">数据库密码</label>
                                    <input type="password" name="db_pass" class="form-control" value="<?= htmlspecialchars($dbPass) ?>">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">数据库名</label>
                                    <input type="text" name="db_name" class="form-control" value="<?= htmlspecialchars($dbName) ?>" required>
                                </div>

                                <button type="submit" name="submit" value="1" class="btn btn-primary btn-lg w-100">
                                    <i class="bi bi-database"></i> 连接并安装数据库
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>